package com.uduemc.biso.node.web.api.validator.currentsite.impl;

import java.io.IOException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.service.SystemService;
import com.uduemc.biso.node.web.api.validator.currentsite.CurrentSiteSystemIdExist;

public class CurrentSiteSystemIdExistValid implements ConstraintValidator<CurrentSiteSystemIdExist, Long> {

	@Override
	public void initialize(CurrentSiteSystemIdExist constraintAnnotation) {

	}

	@Override
	public boolean isValid(Long value, ConstraintValidatorContext context) {
		if (value == null) {
			return false;
		}
		if (value.longValue() == 0) {
			return false;
		}
		SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
		SSystem sSystem = null;
		try {
			sSystem = systemServiceImpl.getInfoById(value);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (sSystem == null) {
			return false;
		}
		if (sSystem.getId().longValue() == value.longValue()) {
			RequestHolder requestHolder = SpringContextUtils.getBean("requestHolder", RequestHolder.class);
			if (requestHolder.getHost().getId().longValue() == sSystem.getHostId().longValue()
					&& requestHolder.getCurrentSite().getId().longValue() == sSystem.getSiteId().longValue()) {
				return true;
			}
			return false;
		}
		return false;
	}

}
